import React, { useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import {
  ArrowLeftIcon,
  StarIcon,
  ArrowDownTrayIcon,
  LinkIcon,
  TagIcon,
  ClockIcon,
  UserIcon,
  DocumentTextIcon,
  ExclamationTriangleIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { fetchPluginById, selectCurrentPlugin, selectPluginsLoading } from '@/store/slices/pluginSlice'
import { Card, Button, Badge, StatusBadge, LoadingSkeleton } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

export const PluginDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const dispatch = useDispatch<AppDispatch>()
  const plugin = useSelector(selectCurrentPlugin)
  const isLoading = useSelector(selectPluginsLoading)

  useEffect(() => {
    if (id) {
      dispatch(fetchPluginById(id))
    }
  }, [dispatch, id])

  if (isLoading) {
    return (
      <div className="max-w-6xl mx-auto space-y-6">
        <div className="flex items-center space-x-4">
          <LoadingSkeleton width="100px" height="40px" />
          <LoadingSkeleton width="300px" height="32px" />
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2">
            <Card className="p-6">
              <LoadingSkeleton lines={8} />
            </Card>
          </div>
          <div>
            <Card className="p-6">
              <LoadingSkeleton lines={6} />
            </Card>
          </div>
        </div>
      </div>
    )
  }

  if (!plugin) {
    return (
      <div className="max-w-6xl mx-auto">
        <Card className="p-12 text-center">
          <ExclamationTriangleIcon className="mx-auto h-16 w-16 text-gray-400 mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">Plugin not found</h3>
          <p className="text-gray-600 mb-6">
            The plugin you're looking for doesn't exist or has been removed.
          </p>
          <Button onClick={() => navigate('/marketplace')} variant="outline">
            Back to Marketplace
          </Button>
        </Card>
      </div>
    )
  }

  // const tabs = [
  //   { id: 'overview', name: 'Overview', icon: DocumentTextIcon },
  //   { id: 'versions', name: 'Versions', icon: CodeBracketIcon },
  //   { id: 'reviews', name: 'Reviews', icon: StarIcon }
  // ]

  return (
    <ErrorBoundary>
      <div className="max-w-6xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex items-center space-x-4">
          <Button
            variant="ghost"
            onClick={() => navigate('/marketplace')}
            icon={<ArrowLeftIcon />}
          >
            Back to Marketplace
          </Button>
        </div>

        {/* Plugin Header */}
        <Card className="p-6">
          <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-6">
            <div className="flex-1">
              <div className="flex items-center space-x-3 mb-4">
                <h1 className="text-3xl font-bold text-gray-900">{plugin.displayName}</h1>
                <StatusBadge status={plugin.status || 'pending'} />
                {plugin.featured && (
                  <Badge variant="warning">Featured</Badge>
                )}
              </div>

              <div className="flex items-center space-x-6 text-sm text-gray-600 mb-4">
                <div className="flex items-center">
                  <UserIcon className="h-4 w-4 mr-1" />
                  by {plugin.developer.displayName || plugin.developer.username}
                </div>
                <div className="flex items-center">
                  <ArrowDownTrayIcon className="h-4 w-4 mr-1" />
                  {plugin.totalDownloads.toLocaleString()} downloads
                </div>
                <div className="flex items-center">
                  <StarIcon className="h-4 w-4 mr-1 text-yellow-400" />
                  {plugin.rating.average.toFixed(1)} ({plugin.rating.count || 0} reviews)
                </div>
                <div className="flex items-center">
                  <ClockIcon className="h-4 w-4 mr-1" />
                  Updated {new Date(plugin.updatedAt).toLocaleDateString()}
                </div>
              </div>

              <p className="text-gray-700 text-lg leading-relaxed mb-6">
                {plugin.description || 'No description available'}
              </p>

              {/* Tags */}
              {plugin.tags && plugin.tags.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-6">
                  {plugin.tags.map((tag) => (
                    <Badge key={tag} variant="gray">
                      <TagIcon className="h-3 w-3 mr-1" />
                      {tag}
                    </Badge>
                  ))}
                </div>
              )}
            </div>

            {/* Install/Action Section */}
            <div className="lg:w-80">
              <Card className="p-6 bg-gray-50">
                <div className="space-y-4">
                  <Button
                    size="lg"
                    fullWidth
                    icon={<ArrowDownTrayIcon />}
                    disabled={plugin.status !== 'approved'}
                  >
                    {plugin.status === 'approved' ? 'Install Plugin' : 'Not Available'}
                  </Button>

                  {plugin.status !== 'approved' && (
                    <div className="flex items-center text-sm text-amber-600 bg-amber-50 p-3 rounded-md">
                      <ExclamationTriangleIcon className="h-4 w-4 mr-2 flex-shrink-0" />
                      This plugin is not yet approved for installation.
                    </div>
                  )}

                  <div className="text-sm text-gray-600 space-y-2">
                    <div className="flex justify-between">
                      <span>Version:</span>
                      <span className="font-medium">{plugin.latestVersion || '1.0.0'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>License:</span>
                      <span className="font-medium">{plugin.license || 'N/A'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Category:</span>
                      <span className="font-medium capitalize">{plugin.category}</span>
                    </div>
                  </div>

                  {/* Links */}
                  <div className="space-y-2 pt-4 border-t border-gray-200">
                    {plugin.repositoryUrl && (
                      <a
                        href={plugin.repositoryUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-sm text-primary-600 hover:text-primary-700"
                      >
                        <LinkIcon className="h-4 w-4 mr-2" />
                        Source Code
                      </a>
                    )}
                    {plugin.homepageUrl && (
                      <a
                        href={plugin.homepageUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-sm text-primary-600 hover:text-primary-700"
                      >
                        <LinkIcon className="h-4 w-4 mr-2" />
                        Homepage
                      </a>
                    )}
                    {plugin.documentationUrl && (
                      <a
                        href={plugin.documentationUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-sm text-primary-600 hover:text-primary-700"
                      >
                        <DocumentTextIcon className="h-4 w-4 mr-2" />
                        Documentation
                      </a>
                    )}
                  </div>
                </div>
              </Card>
            </div>
          </div>
        </Card>
      </div>
    </ErrorBoundary>
  )
}
